package com.mrper.ui.goods;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.miguo.app.AppHelper;
import com.miguo.bean.GoodsBean;
import com.miguo.framework.request.FailData;
import com.miguo.framework.request.JsonData;
import com.miguo.framework.utils.Toast;
import com.miguo.framework.view.LoadingDialog;
import com.miguo.http.HttpClient;
import com.miguo.http.Url;
import com.miguo.ui.R;
import com.miguo.ui.databinding.ActivityGoodsDetailInfoBinding;
import com.mrper.ext.adapter.goods.GoodsGenericAdapter;
import com.mrper.ext.annotation.BackActionEvent;
import com.mrper.ext.annotation.ContentView;
import com.mrper.ext.dialog.ShareActionSheetDialog;
import com.mrper.ext.uibase.BasicActivity;
import com.mrper.ext.widget.ScrollableView;
import com.mrper.model.share.ShareContentWithImageInfoEntry;
import com.mrper.util.ApkUtil;
import com.mrper.util.DensityUtil;
import com.mrper.util.DeviceUtil;
import com.mrper.util.DialogUtil;
import com.mrper.util.ToastUtil;
import com.mrper.util.extra.GoodsUtil;
import com.mrper.util.share.ShareUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**  商品详情页面  **/
@BackActionEvent
@ContentView(R.layout.activity_goods_detail_info)
public class GoodsDetailInfoActivity extends BasicActivity<ActivityGoodsDetailInfoBinding>
        implements AdapterView.OnItemClickListener, ScrollableView.OnScrollListener, View.OnClickListener {

    private ShareActionSheetDialog shareActionSheetDialog;//分享对话框
    private ShareUtil shareUtil;//分享辅助方法
    private GoodsBean goodsInfo;//商品信息
    private boolean isFavorGoods = false;//是否收藏了商品
    private ShareContentWithImageInfoEntry shareContent;//要分享的内容
    private LoadingDialog loadingDialog;//加载对话框
    private boolean isLoadSimilarGoods = false;//未加载商品

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataBinder.setOnClickEvent(this);
        initIntentDataArgument();//初始化数据和参数
        initActivityLayout(); //初始化布局
    }

    @Override
    public boolean isInitHttpCallback() { return false; }

    @Override
    public boolean isInitShowLoadingDialog() { return true; }

    /**  初始化数据和参数  **/
    private void initIntentDataArgument() {
        //获取页面传递的数据
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("goodsinfo")) {
            goodsInfo = (GoodsBean) intent.getSerializableExtra("goodsinfo");
            if (goodsInfo != null) {
                dataBinder.setGoodsInfo(goodsInfo);
                //构建分享数据
                shareContent = new ShareContentWithImageInfoEntry();
                shareContent.title = goodsInfo.getTitle();
                shareContent.desc = goodsInfo.getTitle() + goodsInfo.getShare_url();
                shareContent.image_url = goodsInfo.getPic_url();
                shareContent.url = goodsInfo.getShare_url();
                shareContent.type = 1;//默认恒等于1，标示识微信网页分享
                shareContent.app_name = getString(R.string.app_name);//设置App名称
            }
        }
    }

    /**  初始化布局  **/
    private void initActivityLayout() {
        //初始化分享对话框
        shareUtil = new ShareUtil(this);//分享对象
        shareUtil.initLoadingDialog();//自己生成分享对象
        shareActionSheetDialog = new ShareActionSheetDialog();
        shareActionSheetDialog.setShareUtil(shareUtil);
        //获取屏幕宽度
        int screenWidth = DeviceUtil.getScreenWidth(this);
        //设置图片高度
        LinearLayout.LayoutParams piclp = (LinearLayout.LayoutParams)dataBinder.imgPicture.getLayoutParams();
        int standarWidth = screenWidth * 2 / 3;
        int standarHeight = (int)(standarWidth);
        piclp.width = standarWidth;
        piclp.height = standarHeight;
        dataBinder.imgPicture.setLayoutParams(piclp);
        ViewGroup.LayoutParams containerlp = ((LinearLayout)dataBinder.imgPicture.getParent()).getLayoutParams();
        containerlp.height = standarHeight;
        ((LinearLayout)dataBinder.imgPicture.getParent()).setLayoutParams(containerlp);
        //设置ScrollView监听
        dataBinder.svContainer.setOnScrollListener(this);
        //调整相似产品表格
        dataBinder.stateView.setActivity(this);
        dataBinder.stateView.setContentView(dataBinder.gvSimilarGoods);
        dataBinder.stateView.getRefreshView().setOnClickListener(this);
        dataBinder.stateView.getNetworkView().setOnClickListener(this);
        dataBinder.gvSimilarGoods.setOnItemClickListener(this);
        adjustGoodsImageHeight();//调整图片高度
        initWebView(); //加载对话框
        dealNoWebDetailSituation(); //处理没有web详情的时候，隐藏web组件，加载相似的商品
    }

    /** 处理没有web详情的时候，隐藏web组件，加载相似的商品 **/
    private void dealNoWebDetailSituation() {
        dataBinder.svContainer.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(!isScrollViewScrollable()) {
                    dataBinder.webDetailContainer.setVisibility(View.GONE);
                    if (!isLoadSimilarGoods) {
                        isLoadSimilarGoods = true;
                        loadSimilarGoods();
                    }
                }
            }
        }, 1500);
    }

    /** 调整图片尺寸  **/
    private void adjustGoodsImageHeight() {
        int scrHeight = DeviceUtil.getScreenHeight(this);
        int statusBarHeight = ApkUtil.getStatusBarHeight(this);
        dataBinder.llInfoContainer.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        int infoContaienrHeight = dataBinder.llInfoContainer.getMeasuredHeight();
        int imageHeight = scrHeight - statusBarHeight - infoContaienrHeight - (int) DensityUtil.dip2px(this, 47f + 50f + 60f);
        ViewGroup.LayoutParams imgLayoutParams = dataBinder.imgPicture.getLayoutParams();
        imgLayoutParams.height = imageHeight + (int) DensityUtil.dip2px(this, 2f);
        dataBinder.imgPicture.setLayoutParams(imgLayoutParams);
    }

    private void initWebView(){
        WebSettings settings = dataBinder.webDetail.getSettings();
        settings.setJavaScriptEnabled(true); //设置JavaScript可用
        if(Build.VERSION.SDK_INT >= 11) settings.setDisplayZoomControls(false);
        else settings.setBuiltInZoomControls(false);
        dataBinder.webDetail.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                AppHelper.StartWebView(activity, url);
                return true;
            }
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                DialogUtil.showDialog(loadingDialog);
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                dataBinder.webDetail.loadUrl("javascript:document.getElementsByTagName(\"body\")[0].setAttribute(\"style\",\"padding:5px 3px 5px 3px\");");
                DialogUtil.hideDialog(loadingDialog,false);
            }
        });
        dataBinder.webDetail.loadUrl(Url.toRoute(String.format(Url.ExtUrl.ImageDetail, goodsInfo.getId()), 1));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imgBack://返回
                this.finish();
                overridePendingTransition(R.anim.umeng_fb_slide_in_from_left, 0);
                break;
            case R.id.imgFriendCircle://朋友圈
                shareUtil.startShare(ShareUtil.SHARE_TYPE_WECHAT,shareContent,1);//分享到微信平台 scence: 1.朋友圈 2.微信好友
                break;
            case R.id.imgWechat://微信
                shareUtil.startShare(ShareUtil.SHARE_TYPE_WECHAT,shareContent,2);//分享到微信平台 scence: 1.朋友圈 2.微信好友
                break;
            case R.id.imgMore://更多分享
                showShareActionSheetDialog();//显示分享对话框
                break;
            case R.id.btnCollect://收藏
                operateGoodsFavor();//操作商品收藏
                break;
            case R.id.btnBuy://去淘宝购买
                AppHelper.startGoodsDetailPageByBrandGoodsId(this, goodsInfo.getTitle(), goodsInfo.getItem_id(), goodsInfo.getJump_type());
                break;
            case R.id.refresh_rl://刷新事件
            case R.id.network_error_ll://网络错误事件
                loadSimilarGoods();//加载商品数据
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        GoodsBean item = (GoodsBean)dataBinder.gvSimilarGoods.getItemAtPosition(position);
        AppHelper.startGoodsDetailPage(activity,item);
    }

    @Override
    public void onScrollChanged(int x, int y, int oldX, int oldY) {
        View endView = dataBinder.svContainer.getChildAt(dataBinder.svContainer.getChildCount() - 1);
        int dy = endView.getBottom() - (dataBinder.svContainer.getHeight() + dataBinder.svContainer.getScrollY());
        if(!isLoadSimilarGoods && dy <= 0){
            isLoadSimilarGoods = true;
            loadSimilarGoods();
        }
    }

    /** 判断ScrollView是否可以滚动 **/
    private boolean isScrollViewScrollable(){
        View endView = dataBinder.svContainer.getChildAt(0);
        if(endView != null){
            return dataBinder.svContainer.getHeight() < endView.getHeight();
        }
        return false;
    }

    /**
     * 显示分享对话框
     **/
    private void showShareActionSheetDialog() {
        if (shareActionSheetDialog != null && !shareActionSheetDialog.isVisible()) {
            Bundle data = new Bundle();
            data.putSerializable("shareContent", shareContent);
            shareActionSheetDialog.setArguments(data);
            shareActionSheetDialog.show(getSupportFragmentManager(), ShareActionSheetDialog.TAG);
        }
    }

    /**
     * 操作商品收藏
     **/
    private void operateGoodsFavor() {
        if (goodsInfo != null) {
            GoodsUtil.favorActionWidthoutImageView(this, goodsInfo, !isFavorGoods);
            dataBinder.setIsFavor(!isFavorGoods);
            isFavorGoods = !isFavorGoods;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        resumeCtlState(); //获取当前的收藏状态
    }

    private void resumeCtlState() {
        isFavorGoods = GoodsUtil.isFavor(this, goodsInfo);
        dataBinder.setIsFavor(isFavorGoods);
        GoodsGenericAdapter adapter = (GoodsGenericAdapter)dataBinder.gvSimilarGoods.getAdapter();
        if(adapter!=null) adapter.notifyDataSetChanged();
    }

    /** 加载相似商品 **/
    private void loadSimilarGoods(){
        Map<String,String> params = new HashMap<>();
        params.put("classify_id",String.valueOf(goodsInfo.getClassify_id()));
        if(httpCallback == null) httpCallback = getAjaxCallBack(); //初始化HttpCallback
        HttpClient.post(Url.toRoute(Url.ExtUrl.SimilarGoods, 1), params,httpCallback);
    }

    @Override
    public void onLoadHttpDataSuccessful(JsonData json) {
        super.onLoadHttpDataSuccessful(json);
        if(json.optInt("status") == 200){
            JsonData json_data = json.optJson("data");
            try {
                List<GoodsBean> goods = new Gson().fromJson(
                        json_data.optJson("item").toString(),
                        new TypeToken<ArrayList<GoodsBean>>() {}.getType()
                );
                if (goods != null && goods.size() > 0) //设置商品列表
                    dataBinder.gvSimilarGoods.setAdapter(new GoodsGenericAdapter(context,goods));
                dataBinder.stateView.setRefreshVisibility(View.GONE);
                return;
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            Toast.show(context, json.optString("info"));
        }
        dataBinder.stateView.setRefreshVisibility(View.VISIBLE);
    }

    @Override
    public void onLoadHttpDataFaield(FailData data) {
        super.onLoadHttpDataFaield(data);
        ToastUtil.showShortToast(this, "加载相关其他商品失败，请稍后重试");
        dataBinder.stateView.setRefreshVisibility(View.VISIBLE);
    }

}
